package com.zc.im.rabbitmq;
import com.zc.im.util.properties.RabbitmqProperties;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.CachingConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;


/**
 * Created by Administrator on 2017/7/20.
 */
@Component
public class AmqpConfig {

    @Autowired
    private RabbitmqProperties rabbitmqProperties;

    /**
     * 配置消息交换机
     * 针对消费者配置
     * FanoutExchange: 将消息分发到所有的绑定队列，无routingkey的概念
     * HeadersExchange ：通过添加属性key-value匹配
     * DirectExchange:按照routingkey分发到指定队列
     * TopicExchange:多关键字匹配
     */
    @Bean
    public DirectExchange defaultExchange() {
        return new DirectExchange("DirectExchange", true, false);
    }



    //发送消息队列
    @Bean
    public Queue sendQueue() {
        return new Queue(rabbitmqProperties.getRabbitSendQueueName(), true);//队列持久
    }

    @Bean
    TopicExchange sendExchange() {
        return new TopicExchange(rabbitmqProperties.getRabbitTopicExchange());
    }

    @Bean
    Binding sendMsgBinding() {
        return BindingBuilder.bind(sendQueue()).to(sendExchange()).with(rabbitmqProperties.getRabbitSendQueueName());
    }




    @Bean
    public org.springframework.amqp.rabbit.connection.ConnectionFactory connectionFactory() {
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
        connectionFactory.setHost(rabbitmqProperties.getRabbitHost());
        connectionFactory.setPort(Integer.parseInt(rabbitmqProperties.getRabbitPort()));
        connectionFactory.setUsername(rabbitmqProperties.getRabbitUserName());
        connectionFactory.setPassword(rabbitmqProperties.getRabbitPassWord());
        connectionFactory.setVirtualHost(rabbitmqProperties.getRabbitVirtualHost());
        //这里需要显示调用
        connectionFactory.setPublisherConfirms(true);
        return connectionFactory;
    }
}
